from PyQt4.QtCore import QObject, SIGNAL

from game.judge import judge_winner
import config


class BoardModel(QObject):
    def __init__(self, parent=None):
        super(BoardModel, self).__init__(parent)
        self.run = False
        self.board = newBoard()
        self.history = []
        self.simulate = False

    def send_update(self):
        if not self.simulate:
            self.emit(SIGNAL('boardChanged()'))

    def new_game(self):
        self.board = newBoard()
        self.history = []
        self.run = True
        self.send_update()

    def end_game(self):
        self.run = False

    def get_pos(self, xPos, yPos):
        if 0 <= xPos < config.Len and 0 <= yPos < config.Len:
            return self.board[xPos][yPos]

    def get_last_step(self):
        if self.history.__len__() > 0:
            return self.history[-1]
        else:
            return (None, None, None)

    def new_step(self, xPos, yPos):
        # print('model', xPos, yPos)
        if not self.run:
            return
        if not (0 <= xPos < config.Len and 0 <= yPos < config.Len):
            return
        if self.get_pos(xPos, yPos) != config.ROLES.vacant:
            return
        role = self.get_role()
        self.history.append((xPos, yPos, role))
        self.board[xPos][yPos] = role
        self.send_update()
        result = judge_winner(self)
        if result != config.ROLES.illegal:
            self.emit(SIGNAL('gameOver(int)'), result)

    def retract(self):
        if not self.run:
            return
        if self.history.__len__() == 0:
            return
        xPos, yPos, role = self.history.pop()
        self.board[xPos][yPos] = config.ROLES.vacant
        self.send_update()

    def get_role(self):
        if self.history.__len__() % 2 == 0:
            return config.ROLES.firsthand
        else:
            return config.ROLES.secondhand


def newBoard():
    return [[config.ROLES.vacant for i in range(config.Len)] for j in range(config.Len)]





# def updateBoard(func):
#     def wrapper(self):
#         self.func()
#         self.emit(SIGNAL('boardChanged()'))
#     return wrapper
